package com.xwder.netty.codec2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * netty server use protoc
 *
 * @author xwder
 * @date 2021/3/22 09:26
 **/
public class NettyServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    public static void main(String[] args) throws Exception {

        /* 创建 BoosGroup、WorkerGroup
         *  说明：
         *  1.创建两个线程组 bossGroup 和 workerGroup
         *  2.bossGroup 只是处理连接请求 , 真正的和客户端业务处理，会交给 workerGroup 完成
         *  3.两个都是无限循环
         *  4.bossGroup 和 workerGroup 含有的子线程(NioEventLoop)的个数 默认实际为 核心数*2
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            // 创建服务器端的启动对象，配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 使用链式编程来进行设置 首先设置bossGroup 和 workerGroup
            serverBootstrap.group(bossGroup, workGroup)
                    // 使用 NioServerSocketChannel 作为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // .handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
                    // //创建一个通道初始化对象(匿名对象)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            logger.info("客户端socketChannel hashCode:{}", socketChannel.hashCode());
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            //指定对哪种对象进行解码
                            pipeline.addLast("decoder", new ProtobufDecoder(MyDataInfo.MyMessage.getDefaultInstance()));
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            logger.info("netty server is ready ~~");

            // 启动服务器(并绑定端口),绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
            ChannelFuture channelFuture = serverBootstrap.bind(6666).sync();
            // //给 channelFuture 注册监听器，监控我们关心的事件
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) {
                    if (channelFuture.isSuccess()) {
                        logger.info("netty server 监听端口6666 成功~~~");
                    } else {
                        logger.error("netty server 监听端口6666 失败~~~");
                    }
                }
            });

            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅关闭 bossGroup,workGroup
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
